package Chuong04;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class Bai04 extends JFrame implements ActionListener{

	JButton btnTinh = new JButton("Tính");
	JButton btnThoat = new JButton("Thoát");
	
	JLabel lblW, lblH, lblP, lblS;
	JTextField txtW, txtH, txtP, txtS;
	
	public Bai04(){
		setSize(400, 160);
	    setTitle("Bài 04 - Chương 04");
	    btnTinh.addActionListener(this);
	    btnThoat.addActionListener(this);
	    Container container = getContentPane();
	    
	    JPanel p = new JPanel();
	    p.setLayout(new GridLayout(4, 3));
	    
	    lblW = new JLabel("Nhập chiều dài:");
	    lblH = new JLabel("Nhập chiều rộng:");
	    lblP = new JLabel("Chu vi:");
	    lblS = new JLabel("Diện tích:");
	    
	    txtW = new JTextField();
	    txtH = new JTextField();
	    txtP = new JTextField();
	    txtS = new JTextField();
	    
	    //txtP.setEnabled(false);
	    //txtS.setEnabled(false);
	    
	    p.add(lblW); p.add(txtW); p.add(new JLabel());	    
	    p.add(lblH); p.add(txtH); p.add(btnTinh); 
	    p.add(lblP); p.add(txtP); p.add(new JLabel()); 
	    p.add(lblS); p.add(txtS); p.add(btnThoat);
	   
	    
	    container.add(p, BorderLayout.CENTER);
	}
	
	public static void main(String[] args) {
		Bai04 frm = new Bai04();
		frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frm.setVisible(true);
	}

	@Override
	public void actionPerformed(ActionEvent arg0) {
		if(arg0.getSource() == btnThoat){
			System.exit(0);
		}
		
		if(arg0.getSource() == btnTinh){
			try
			{
				int w = Integer.parseInt(txtW.getText());
				int h = Integer.parseInt(txtH.getText());
				int P = 2 * w * h;
				int S = w * h;
				txtP.setText(String.valueOf(P));
				txtS.setText(String.valueOf(S));
			}catch (Exception e) {
				JOptionPane.showMessageDialog(this,"Vui lòng kiểm tra lại nhập liệu!", "Lỗi",JOptionPane.ERROR_MESSAGE);
			}
		}
	}

}
